package com.example.noobpackage.ui

import androidx.lifecycle.*
import com.example.noobpackage.logic.model.ApplicationUser
import com.example.noobpackage.logic.model.ExpressData
import com.example.noobpackage.logic.model.MarketPackageData
import com.example.noobpackage.logic.repository.ExpressRepository
import com.example.noobpackage.logic.repository.MarketRepository
import com.example.noobpackage.tool.LocalUserUtil
import com.example.noobpackage.ui.selfpackage.SelfPackageFragment
import kotlinx.coroutines.launch
import java.util.ArrayList

class MainViewModel : ViewModel() {

    // 展示的全部快递数据
    val allExpressList = ExpressRepository.getAllExpress()

    // 全局用户数据
    private val _userInfo = MutableLiveData<ApplicationUser?>()
    val userInfo: LiveData<ApplicationUser?>
        get() = _userInfo

    init {
        _userInfo.postValue(LocalUserUtil.getUserInfo())
    }

    fun updateUserInfo(applicationUser: ApplicationUser) {
        _userInfo.value = applicationUser
        viewModelScope.launch {
            LocalUserUtil.storageUserInfo(applicationUser)
        }
    }

    fun reloadUserInfo() {
        _userInfo.postValue(LocalUserUtil.getUserInfo())
    }

    fun reloadExpress(){
        viewModelScope.launch {
            ExpressRepository.clearOnlineExpress()
        }
    }

    fun getExpress(position: Int): ExpressData? {
        return allExpressList.value?.get(position)
    }

    fun updateOnlineExpress() {
        viewModelScope.launch {
            userInfo.value?.let { ExpressRepository.loadOnlineExpress(it.account) }
        }
    }

    // 获取某一个代取请求详细信息
    fun getMarketPackage(position: Int): MarketPackageData? {
        return MarketRepository.getPackage(position)
    }

}